package com.dim.list_orders;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class filtr extends Activity {

	private SQLiteDatabase database;
	private ListView listView;
	private Cursor cursor;
	private String table;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(com.dim.list_orders.R.layout.list_save);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				com.dim.list_orders.R.layout.title);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText(com.dim.list_orders.R.string.l_filtr);

		Bundle extras = getIntent().getExtras();
		if (extras.isEmpty() == false) {
			table = extras.getString("table");
		}

		listView = (ListView) findViewById(R.id.list);
		class_sqlite dbOpenHelper = new class_sqlite(this,
				getString(com.dim.list_orders.R.string.db_name));
		database = dbOpenHelper.openDataBase();

		get_cursor_all();
	}

	private void get_cursor_all() {
		stopManagingCursor(cursor);
		cursor = database.query(table, new String[] { "_id", "name", "show" },
				null, null, null, null, "name");
		startManagingCursor(cursor);

		cursor.moveToFirst();
		ArrayList<String> todoItems = new ArrayList<String>();
		for (int i = 0; i < cursor.getCount(); i++) {
			todoItems.add(cursor.getString(cursor.getColumnIndex("name")));
			cursor.moveToNext();
		}

		listView.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_checked, todoItems));
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		cursor.moveToFirst();
		for (int i = 0; i < cursor.getCount(); i++) {
			if (cursor.getInt(cursor.getColumnIndex("show")) == 1) {
				listView.setItemChecked(i, true);
			}
			cursor.moveToNext();
		}

	}

	public void b_add(View v) {
		cursor.moveToFirst();
		for (int i = 0; i < cursor.getCount(); i++) {
			ContentValues initialValues = new ContentValues();

			if (listView.isItemChecked(i)) {
				initialValues.put("show", 1);
			} else {
				initialValues.put("show", 0);
			}
			String[] args = { String.valueOf(cursor.getInt(cursor
					.getColumnIndex("_id"))) };
			database.update(table, initialValues, "_id=?", args);
			cursor.moveToNext();
		}
		onBackPressed();
	}

	protected void onDestroy() {
		super.onDestroy();
		database.close();
	}

}
